package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.*;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class DeleteSeletedServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";
    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        Cart cart = (Cart)session.getAttribute("cart");
        AddCart addCart = (AddCart) session.getAttribute("addCart");
        AccountService accountService = new AccountService();


        //将数据库中购物车商品数量置位0

        Iterator<CartItem> cartItems = cart.getAllCartItems();
//        Iterator<CartItem> addCartItems = addCart.getAllCartItems();

        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            System.out.println(itemId);
            try {
                Iterator<CartItem> addCartItems = addCart.getAllCartItems();
                while(addCartItems.hasNext()){
                    CartItem addCartItem = (CartItem) addCartItems.next();
                    try{
                        String Id = addCartItem.getItem().getItemId();
                        if(Id.equals(itemId)){
                            System.out.println(itemId);
                            cart.setQuantityByItemId(itemId, 0);
                            addCart.setQuantityByItemId(itemId, 0);
                            accountService.ReserveCart(loginAccount,cart);
                            cart.removeItemById(itemId);
                            addCart.removeItemById(itemId);
//                            cartItems.remove();
//                            addCartItems.remove();
                        }
                    }catch (Exception e){}
                }

            } catch (Exception e) {}
        }

        req.getRequestDispatcher(CART_FORM).forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
